package cn.zifangsky.hashtable.lfu;

import org.junit.Test;

/**
 * 测试用例
 *
 * @author zifangsky
 * @date 2020/6/25
 * @since 1.0.0
 */
public class TestDemo {

    @Test
    public void testMethod1() {
        LFUCache<String, Integer> lfuCache = new LFUCache<>(3, false);

        lfuCache.put("A", 1);
        lfuCache.put("B", 2);
        lfuCache.put("C", 3);
        System.out.println(String.format("B被连续访问3次：%d - %d - %d", lfuCache.get("B"), lfuCache.get("B"), lfuCache.get("B")));
        System.out.println(String.format("A被连续访问2次：%d - %d", lfuCache.get("A"), lfuCache.get("A")));

        //此时因为缓存容量不够C会被清除
        lfuCache.put("D", 4);
        System.out.println("********** 添加 D 后的结果 **********");
        lfuCache.forEach(node -> System.out.println(String.format("%s-->%d, times: %d", node.key, node.value, node.times)));

        lfuCache.remove("A");
        System.out.println("********** 移除 A 后的结果 **********");
        lfuCache.forEach(node -> System.out.println(String.format("%s-->%d, times: %d", node.key, node.value, node.times)));
    }

    @Test
    public void testMethod2() throws Exception {
        LFUCache<String, String> lfuCache = new LFUCache<>(3);

        lfuCache.put("A", "10", -1);
        lfuCache.put("B", "20", 5);
        lfuCache.put("C", "30", 30);
        System.out.println("B的值是：" + lfuCache.get("B"));
        System.out.println("A的值是：" + lfuCache.get("A"));

        //暂停6秒钟，让B过期被清除
        Thread.sleep(6000);
        lfuCache.put("D", "40", 30);
        System.out.println("********** 暂停6秒钟后 **********");
        lfuCache.forEach(node -> System.out.println(String.format("%s-->%s, times: %d", node.key, node.value, node.times)));

        System.out.println("********** 第二次结果 **********");
        System.out.println(String.format("D被连续访问2次：%s - %s", lfuCache.get("D"), lfuCache.get("D")));
        System.out.println(String.format("A被连续访问1次：%s", lfuCache.get("A")));
        System.out.println(String.format("C被连续访问1次：%s", lfuCache.get("C")));
        lfuCache.forEach(node -> System.out.println(String.format("%s-->%s, times: %d", node.key, node.value, node.times)));

        //此时因为缓存容量不够C会被清除
        lfuCache.put("E", "50", 30);
        System.out.println("********** 第三次结果 **********");
        lfuCache.forEach(node -> System.out.println(String.format("%s-->%s, times: %d", node.key, node.value, node.times)));
    }

}
